import store from '@/store/index'

const url = process.env.VITE_API_URL

interface options {
  url: string
  data?: object
}

export function beOver() {
  // 重新登录
  uni.removeStorageSync('token')
  uni.removeStorageSync('userInfo')
  // store.dispatch('app/IM_DESTROY')
}
let currentRequest = null
function post(options: options): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    let token = uni.getStorageSync('token')
    if (options.banRepeatCancel == true) {
      currentRequest.abort() // 取消上一个请求
    }
    currentRequest = uni.request({
      url: url + options.url,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        clientType: store.state.CLIENTTYPE,
        // Authorization: store.state.token,
        Authorization: token,
        orgId: 2
      },
      timeout: 30000,
      data: options.data,
      dataType: 'json',
      success: (respones: any) => {
        if (respones.statusCode == 200) {
          if (respones.data.code !== 0) {
            if (respones.data.code === 401) {
              uni.hideLoading()
              uni.showToast({
                title: '您当前的登录信息已过期，即将返回登录页',
                icon: 'none',
                duration: 3000,
                success: (res) => {
                  beOver()
                  setTimeout(() => {
                    uni.reLaunch({
                      url: '/pages/login/index'
                    })
                  }, 3000)
                }
              })
              reject(respones.data)
            } else {
              uni.showToast({
                icon: 'none',
                title: respones.data.msg,
                duration: 2000
              })
              reject(respones.data)
            }
          }
          return resolve(respones.data)
        } else if (respones.statusCode == 401) {
          uni.showToast({
            title: '您当前的登录信息已过期，即将返回登录页',
            icon: 'none',
            duration: 3000,
            success: (res) => {
              beOver()
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/login/index'
                })
              }, 3000)
            }
          })
          reject()
        } else {
          reject()
        }
      },
      fail: (err) => {
        // uni.showToast({
        //     title: '请求失败',
        //     icon: 'error'
        // })
        console.log(err)
        reject()
        // throw new Error('请求失败');
      },
      complete: () => {}
    })
  })
}

export default {
  // get: get,
  post: post
}
